package com.hfp.mall.product.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hfp.mall.common.util.BeanUtil;
import com.hfp.mall.common.util.ResultVOUtil;
import com.hfp.mall.common.vo.ResultVo;
import com.hfp.mall.common.vo.ReturnPageData;
import com.hfp.mall.product.entity.Product;
import com.hfp.mall.product.form.ProductForm;
import com.hfp.mall.product.form.ProductSearch;
import com.hfp.mall.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 商品信息表 前端控制器
 * </p>
 *
 * @author lzc
 * @since 2019-01-22
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Autowired
    private IProductService productService;

    @GetMapping("/products")
    public ResultVo productList(@RequestParam(name = "pageNum", defaultValue = "1")Integer pageNum,
                                @RequestParam(name = "pageSize", defaultValue = "10")Integer pageSize,
                                ProductSearch productSearch) {
        Page<Product> productPage = new Page<>(pageNum,pageSize);

        productService.page(productPage,new QueryWrapper<Product>().allEq(BeanUtil.Bean2Map(productSearch),false));

        return ResultVOUtil.success(new ReturnPageData(productPage, pageNum, pageSize));
    }

    @PostMapping("/products")
    public ResultVo addProduct(ProductForm productForm) {
        productForm.setId(null);
        Product product = new Product();

        BeanUtils.copyProperties(productForm, product);

        product.setMerchantId(1);
        product.setMerchantName("桂林米粉店");

        productService.save(product);
        return ResultVOUtil.success();
    }

    // 商家修改
    @PostMapping("/products/edit")
    public ResultVo edit(ProductForm productForm) {
        Product result = productService.getById(productForm.getId());
        // 判断该商品是否属于自己的，只能修改自己的商品，后面再实现

        BeanUtils.copyProperties(productForm, result);
        result.setUpdateTime(new Date());
        productService.updateById(result);

        return ResultVOUtil.success();
    }

    @GetMapping("/products/id")
    public ResultVo product(@RequestParam Integer id) {
        if (id == null) {
            return ResultVOUtil.error(-1, "id不能为空");
        }
        return ResultVOUtil.success(productService.getById(id));
    }

}
